
<!-- 是templete 不是  templete -->
<template>
  <div>
    <!-- 面包屑导区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <!-- :to="{ path: '/homePage' }" -->
      <el-breadcrumb-item :to="{ path: '/homePage' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert
        title="注意！ 只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <el-row class="cate">
        <el-col>
          <span>选择商品分类: &nbsp;</span>
          <el-cascader
            v-model="selectKeys"
            :options="cateList"
            :props="{ expandTrigger: 'hover', ...cascaderProps }"
            @change="handleChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeTabName" @tab-click="handleTabClick">
        <!--标签页1 disabled属性对 2种值的引用 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            :disabled="selectKeys.length !== 3"
            @click="addCateDialogVisible = true"
            >添加参数</el-button
          >

          <!-- 长度等于3时才有数据 ，清空数据时列表无数据
          :data="selectKeys.length === 3?tabData: []" -->
          <el-table
            :data="selectKeysLength === 3 ? tabData : []"
            stripe
            :border="true"
          >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  @close = "deleteAttrVal(scope.row,i)"
                  >{{ item }}</el-tag
                >

                <!-- 文本输入按钮 
                @blur="handleInputConfirm" 文本框失去焦点后
                v-if="inputVisible"
                ref="saveTagInput"
                -->
                <el-input
                  :id ="scope.row.attr_id"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>

                <!-- 新选项标签按钮 -->
                <el-button
                :id ="scope.row.attr_id"
                v-else size="small" @click="showInput(scope.row)"
                  >+ New Tag</el-button>
                
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <!-- <el-table-column prop="attr_id" label="id"></el-table-column> -->
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="openEditCateDialog(scope.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="remove(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 标签页2 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            :disabled="isBtnDisabled"
            @click="addCateDialogVisible = true"
            >添加属性</el-button
          >

          <el-table
            :data="selectKeysLength === 3 ? tabData : []"
            stripe
            :border="true"
          >
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(item, i) in scope.row.attr_vals"
                  :key="i"
                  >{{ item }}</el-tag
                >

                <!-- 文本输入按钮 
                @blur="handleInputConfirm" 文本框失去焦点后
                v-if="inputVisible"
                ref="saveTagInput"
                -->
                <el-input
                 :id ="scope.row.attr_id"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>

                <!-- 新选项标签按钮 -->
                <el-button
                v-else size="small" @click="showInput(scope.row)"
                  >+ New Tag</el-button>


              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="openEditCateDialog(scope.row)"
                  >编辑</el-button
                >

                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="remove(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-dialog
      :title="'添加' + getCurrentDialogTitle"
      :visible.sync="addCateDialogVisible"
      @close="closeAddCateDialog"
      width="30%"
    >
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="80px"
      >
        <el-form-item :label="getCurrentDialogTitle" prop="attr_name">
          <el-input v-model="addCateForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑框 -->
    <el-dialog
      :title="'编辑' + getCurrentDialogTitle"
      :visible.sync="editCateDialogVisible"
      @close="closeEditCateDialog"
    >
      <el-form
        :model="editCateForm"
        :rules="editCateFormRules"
        ref="editCateFormRef"
        label-width="80px"
      >
        <el-form-item :label="getCurrentDialogTitle" prop="attr_name">
          <el-input v-model="editCateForm.attr_name"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
    
    <script>
export default {
  data() {
    //数据区
    return {
      selectKeys: [],
      cateList: [],

      // 级联选择器属性
      cascaderProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },

      // 必须和其中一个tab的名称 相同
      activeTabName: "many",

      tabData: [],
      addCateDialogVisible: false,
      addCateForm: {
        attr_name: "",
      },

      editCateForm: {
        attr_id: "",
        attr_name: "",
      },

      addCateFormRules: {
        attr_name: [{ required: true, message: "请输入内容", trigger: "blur" }],
      },

      editCateFormRules: {
        attr_name: [{ required: true, message: "请输入内容", trigger: "blur" }],
      },

      editCateDialogVisible: false,
      inputVisible: false,
      inputValue: "",
    };
  },

  //方法区
  methods: {
    // 方法1
    async getCateList() {
      const { data: resData } = await this.$http.get("categories");
      if (resData.meta.status !== 200) {
        return this.$message.error(resData.meta.msg);
      }
      this.cateList = resData.data;
    },

    async getCateListV2() {
      return this.cateList;
    },

    

    //方法2
    handleChange() {
      console.log('方法2')
      this.getParamsChange();
    },

    // 方法3
    handleTabClick() {
      console.log(this.activeTabName);
      this.tabData = [];
      this.getParamsChange();
    },

    async getParamsChange() {
      if (this.selectKeys.length !== 3) {
        return;
      }
      const { data: resData } = await this.$http.get(
        `categories/${this.getCateId}/attributes`,
        { params: { sel: this.activeTabName } }
      );
      if (resData.meta.status !== 200) {
        return this.$message.error(resData.meta.msg);
      }
      
      
      resData.data.forEach((ele) => {
        ele.attr_vals = ele.attr_vals !== "" ? ele.attr_vals.split(",") : [];
        ele.inputVisible = false
        ele.inputValue = ''
      });

      //必须将resData.data数据处理完成之后赋值给this.tabData,绝对禁止拿this.tabData
      //直接做数据处理(foreach),会有意料之外的问题(本例中Tag与输入框不能正常切换)
      this.tabData = resData.data

      console.log(this.tabData)
      
 
    },

    // 打开编辑对话框
    async openEditCateDialog(row) {
      // 第一种方法
      // const { data: resData } = await this.$http.get(
      //   `categories/${this.getCateId}/attributes/${attrId}`,
      //   { params: { attr_sel: this.activeTabName } }
      // );
      // if (resData.meta.status !== 200) {
      //   return this.$message.error(resData.meta.msg);
      // }
      // this.editCateForm = resData.data

      // 第二种方法
      // 编辑回显的内容如果table表格里面都有,就无须再去网络请求数据
      this.editCateForm = row;
      this.editCateDialogVisible = true;
      
    },

    // 提交编辑方法
    async editCate() {
      const { data: resData } = await this.$http.put(
        `categories/${this.getCateId}/attributes/${this.editCateForm.attr_id}`,
        { attr_name: this.editCateForm.attr_name, attr_sel: this.activeTabName }
      );
      if (resData.meta.status !== 200) {
        return this.$message.error(resData.meta.msg);
      }
      this.getParamsChange();
      this.editCateDialogVisible = false;
    },

    closeAddCateDialog() {
      this.$refs.addCateFormRef.resetFields();
    },
    closeEditCateDialog() {
      this.$refs.editCateFormRef.resetFields();
    },

    addCate() {
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: resData } = await this.$http.post(
          `categories/${this.getCateId}/attributes`,
          {
            attr_name: this.addCateForm.attr_name,
            attr_sel: this.activeTabName,
          }
        );

        if (resData.meta.status !== 201) {
          return this.message.error(resData.meta.msg);
        }
        this.getParamsChange();
        this.$message.success(resData.meta.msg);
        this.addCateDialogVisible = false;
      });
    },

    // 删除方法
    async remove(row) {
      console.log("1111111111111");
      const confirmResult = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult === "cancel") return this.$message.info("已取消删除");
      const { data: resData } = await this.$http.delete(
        `categories/${this.getCateId}/attributes/${row.attr_id}`
      );
      if (resData.meta.status !== 200) {
        return this.$message.error(resData.meta.msg);
      }
      this.$message.success(resData.meta.msg);
      this.getParamsChange();
    },

    
    // 失去焦点之后执行的方法
     handleInputConfirm(row) {
      row.inputVisible = false;
      this.inputVisible = false
      if(row.inputValue.trim().length === 0){
        return
      }
      
      row.attr_vals.push(row.inputValue)
      this.updateAttrVals(row)
      // 之后清空inputValue
      row.inputValue = ''
      
    },
    
    // 删了属性的方法
    deleteAttrVal(row,i){
      row.attr_vals.splice(i,1)
      this.updateAttrVals(row)

    },

    
    // 更新分类属性方法
    async updateAttrVals(row){
     
      const {data: resData} = await this.$http.put(`categories/${this.getCateId}/attributes/${row.attr_id}`,
      {
        attr_name: row.attr_name,
        attr_sel: this.activeTabName,
        attr_vals: row.attr_vals.join(',')
      }
      )
      if (resData.meta.status !== 200) {
        return this.$message.error(resData.meta.msg)
      }
      this.$message.success(resData.meta.msg)
    },
    showInput(row) {
      row.inputVisible = true
      // 1.让文本框自动获得焦点
      // $nextTick 方法的作用，就是当页面上元素被重新渲染之后，才会指定回调函数中的代码
      // this.$nextTick(_ => {
      //   this.$refs.saveTagInput.$refs.input.focus()
      // })

      //2.让文本框自动获得焦点
      this.$nextTick(() => {
            // this.$refs.saveTagInput.focus();
            document.getElementById(row.attr_id).focus()
      });
      
      //3.让文本框自动获得焦点
      //this.$refs.saveTagInput.focus()
    },
    
     // 睡眠1秒   n=1000
     async sleep(n) {
      var start = new Date().getTime();
      while (true) {
        if (new Date().getTime() - start > n) {
          break;
        }
      }
    },

  },

  //钩子函数
  created() {
    this.getCateList();
  },

  // 获得计算属性
  computed: {
    isBtnDisabled() {
      return this.selectKeys.length === 3 ? false : true;
    },
    getCateId() {
      if (this.selectKeys.length === 3) {
        return this.selectKeys[this.selectKeys.length - 1];
      }
      return null;
    },
    getCurrentDialogTitle() {
      if (this.activeTabName === "many") {
        return "动态参数";
      } else {
        return "静态属性";
      }
    },

    //监听数组长度的变化
    selectKeysLength() {
      // console.log('**** is selectKeysLength')
      this.getParamsChange();
      return this.selectKeys.length;
    },
  },
};
</script>
    
  <style lang="less" scoped>
.cate {
  margin-top: 15px;
  margin-bottom: 15px;
}

.el-tag {
  margin: 5px;
}
.el-input {
  width: auto;
}
</style>